package com.hduong.springcloud.controller;



import com.hduong.springcloud.service.PaymentService;
import entities.CommonResult;
import entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author admin
 */
@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    //要使用服务发现 必须要先启用 这个是Spring Boot的机制
    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    PaymentService paymentService;
    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment){
        boolean save = paymentService.save(payment);
        log.info("插入结果"+save);
        if(payment!=null){
            return  new CommonResult(200,"插入成功");
        }else{
            return  new CommonResult(444,"插入失败");
        }
    }
    @GetMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Integer id){
        Payment payment = paymentService.getById(id);
        log.info("查询结果为：{}",payment);
        if(payment!=null){
            return  new CommonResult(200,"查询成功",payment);
        }else{
            return  new CommonResult(444,"查询为空");
        }
    }

    @GetMapping("/payment/lb")
    public CommonResult paymentLb() {
        return new CommonResult(200, "查询成功， 端口: " + serverPort);
    }

    @GetMapping("/getPort")
    public CommonResult getPort() {
        return new CommonResult(200, "查询成功， 端口: " + serverPort);
    }

    @GetMapping("/discovery")
    public Object  discovery() {
        List<String> services =  discoveryClient.getServices();
        for (String e : services) {
            System.out.println(e);
        }
//        List<String> pay = services.get("BEFORE-CLOUD-PAYMENT-SERVICE");
        List<ServiceInstance> instances =  discoveryClient.getInstances("BEFORE-CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        return this.discoveryClient;
    }

}

